﻿using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Web.Http;
using WebFormsIdentity.Models;
using Microsoft.Owin.Security;
using System.Security.Claims;
using System.Web.UI.WebControls;
using System.Web;

namespace WebFormsIdentity.WebApis
{
    public class LoginApiController : ApiController
    {
        public string GetMessage()
        {
            // 获取当前 Windows 身份
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            // 创建 WindowsPrincipal 对象
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            // 检查当前用户是否是管理员
            bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            // 输出结果
            return $"当前用户：{identity.Name}，是否是管理员：{isAdmin}";
        }

        [HttpPost]
        public MessageInfo UserLogin(LoginData loginData)
        {
            MessageInfo result = new MessageInfo();
            if (loginData == null)
            {
                result.Success = false;
                result.Message = "登录失败";
                return result;
            }
            else
            {
                UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
                UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(userStore);
                IdentityUser user = userManager.Find(loginData.LoginName, loginData.Password);
                if (user != null)
                {
                    IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    Claim claim = new Claim("RoleId", loginData.RoleId.ToString());
                    userIdentity.AddClaim(claim);
                    claim = new Claim("UserName", loginData.UserName);
                    userIdentity.AddClaim(claim);
                    claim = new Claim("MobilePhone", loginData.MobilePhone);
                    userIdentity.AddClaim(claim);
                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);
                    result.Success = true;
                    result.Message = "登录成功";
                }
                else
                {
                    result.Success = false;
                    result.Message = "用户名或密码错误";
                }
                return result;
            }
        }
    }
}